import fs from '../fs'
import path from '../../node/path'
import errorCode from '../../node/error-code'
import { checkError } from '../../universalify'

function getStats (src, dest, opts): any {
    const statFunc = opts.dereference
        ? (file) => fs.stat(file)
        : (file) => fs.lstat(file)
    return Promise.all([
    statFunc(src),
    statFunc(dest).catch(err => {
        if (err.message === errorCode.errormessage.ENOENT) return null
        throw err
    })
    ]).then(([srcStat, destStat]) => ({ srcStat, destStat }))
}

function getStatsSync (src, dest, opts) {
    let destStat
    const statFunc = opts.dereference
        ? (file) => fs.statSync(file,)
        : (file) => fs.lstatSync(file,)
    const srcStat = statFunc(src)
    try {
        destStat = statFunc(dest)
    } catch (err) {
        if (err.message === errorCode.errormessage.ENOENT) return { srcStat, destStat: null }
        throw err
    }
    return { srcStat, destStat }
}

function checkPaths (src, dest, funcName, opts, cb) {
    getStats(src, dest, opts).then((stats) => {
        const { srcStat, destStat } = stats

        if (destStat) {
            if (areIdentical(srcStat, destStat)) {
                const srcBaseName = path.basename(src)
                const destBaseName = path.basename(dest)
                if (funcName === 'move' &&
                srcBaseName !== destBaseName &&
                srcBaseName.toLowerCase() === destBaseName.toLowerCase()) {
                    return cb(null, { srcStat, destStat, isChangingCase: true })
                }
                return cb(new Error('Source and destination must not be the same.'))
            }
            if (srcStat.isDirectory() && !destStat.isDirectory()) {
                return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`))
            }
            if (!srcStat.isDirectory() && destStat.isDirectory()) {
                return cb(new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`))
            }
        }

        if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
            return cb(new Error(errMsg(src, dest, funcName)))
        }
        return cb(null, { srcStat, destStat })
    }).catch(err => {
        if (checkError(err)) return cb(err)
    })
}

function checkPathsSync (src, dest, funcName, opts) {
    const { srcStat, destStat } = getStatsSync(src, dest, opts)

    if (destStat) {
        if (areIdentical(srcStat, destStat)) {
            const srcBaseName = path.basename(src)
            const destBaseName = path.basename(dest)
            if (funcName === 'move' &&
            srcBaseName !== destBaseName &&
            srcBaseName.toLowerCase() === destBaseName.toLowerCase()) {
                return { srcStat, destStat, isChangingCase: true }
            }
            throw new Error('Source and destination must not be the same.')
        }
        if (srcStat.isDirectory() && !destStat.isDirectory()) {
            throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)
        }
        if (!srcStat.isDirectory() && destStat.isDirectory()) {
            throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)
        }
    }

    if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
        throw new Error(errMsg(src, dest, funcName))
    }
    return { srcStat, destStat }
}

// recursively check if dest parent is a subdirectory of src.
// It works for all file types including symlinks since it
// checks the src and dest inodes. It starts from the deepest
// parent and stops once it reaches the src parent or the root path.
function checkParentPaths (src, srcStat, dest, funcName, cb) {
    const srcParent = path.dirname(src)
    const destParent = path.dirname(dest)
    if (destParent === srcParent || destParent === path.parse(destParent).root) return cb()
    fs.stat(destParent, (err, destStat) => {
        if (checkError(err)) {
            if (err.message === errorCode.errormessage.ENOENT) return cb()
            return cb(err)
        }
        if (areIdentical(srcStat, destStat)) {
            return cb(new Error(errMsg(src, dest, funcName)))
        }
        return checkParentPaths(src, srcStat, destParent, funcName, cb)
    })
}

function checkParentPathsSync (src, srcStat, dest, funcName) {
    const srcParent = path.dirname(src)
    const destParent = path.dirname(dest)
    if (destParent === srcParent || destParent === path.parse(destParent).root) return;
    let destStat
    try {
        destStat = fs.statSync(destParent)
    } catch (err) {
        if (err.message === errorCode.errormessage.ENOENT) return;
        throw err
    }
    if (areIdentical(srcStat, destStat)) {
        throw new Error(errMsg(src, dest, funcName))
    }
    return checkParentPathsSync(src, srcStat, destParent, funcName)
}

function areIdentical (srcStat, destStat) {
    return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev
}

// return true if dest is a subdir of src, otherwise false.
// It only checks the path strings.
function isSrcSubdir (src, dest) {
    const srcArr = path.resolve(src).split(path.sep).filter(i => i)
    const destArr = path.resolve(dest).split(path.sep).filter(i => i)
    return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true)
}

function errMsg (src, dest, funcName) {
    return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`
}

export default {
    checkPaths,
    checkPathsSync,
    checkParentPaths,
    checkParentPathsSync,
    isSrcSubdir,
    areIdentical
}
